package com.yy.utils;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: chen
 * @Date: 2022/9/24 21:56
 * @Desc:
 */
@Component
public class ZkClient {

    private ZooKeeper zooKeeper;

    /**
     * 在对象无参构造调用之后,获取zk连接
     */
    @PostConstruct
    public void init() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            zooKeeper = new ZooKeeper("singlenode:2181", 30000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {

                    if (Event.KeeperState.SyncConnected.equals(event.getState()) && Event.EventType.None.equals(event.getType())) {
                        System.out.println("获取连接: " + event);
                        countDownLatch.countDown();
                    } else if (Event.KeeperState.Closed.equals(event.getState())) {
                        System.out.println("关闭连接: " + event);
                    } else {
                        System.out.println("触发监听: " + event);
                    }
                }
            });

            countDownLatch.await();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在容器销毁之前,关闭zk连接
     */
    @PreDestroy
    public void destroy() {
        if (null != zooKeeper) {
            try {
                zooKeeper.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public ZooKeeper getZooKeeper() {
        return zooKeeper;
    }
}
